package com.junzhiit.nengji.shop.web.util.wechat;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.bainaeco.framework.util.JsonUtil;
import com.junzhiit.nengji.model.WechatConfig;
import com.junzhiit.nengji.shop.web.util.Constants;
import com.junzhiit.nengji.shop.web.util.wechat.bean.AccessToken;
import com.junzhiit.nengji.shop.web.util.wechat.bean.TemplateMessageParam;


public class TemplateMessageUtil {
	
	private static Log logger = LogFactory.getLog(TemplateMessageUtil.class);
	
	public final static String ORDERS_SEND = "G145zdRDtzlUfzm3JR2p_cfrfmDYRFeg7Yhb2R2C5Yc"; //订单发货通知
	
	public final static String BUY_SUCCESS = "vhDXiebPdNokLa_vO-cVHATGdYunqihU3kidX97Z8i0";//购买成功
	
	public static Map<String, Object> getMessageData(String... keywords){
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> mapValue = new HashMap<String, Object>();
		for(int i = 1,len = keywords.length; i<= len; i++){
			mapValue = new HashMap<String, Object>();
			mapValue.put("value", keywords[i-1]);
			map.put("keyword"+i, mapValue);
		}
		mapValue = new HashMap<String, Object>();
		return map;
	}
	
	public static void pullMessage(TemplateMessageParam templateMessageParam,WechatConfig wechatConfig){
		AccessToken accessToken = WeChatUtils.getAccessToken(wechatConfig);
		StringBuilder url = new StringBuilder(Constants.URL_TEMPLATE_SEND);
		url.append("?access_token=").append(accessToken.getAccessToken());
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("touser", templateMessageParam.getTouser());
		param.put("template_id", templateMessageParam.getTemplateId());
		param.put("form_id", templateMessageParam.getFormId());
		param.put("page", Constants.TEMPLATE_URL);
		if(StringUtils.isNoneBlank(templateMessageParam.getEmphasisKeyword())){
			param.put("emphasis_keyword", templateMessageParam.getEmphasisKeyword());
		}
		param.put("data", templateMessageParam.getData());
		String json = JsonUtil.toJson(param);
		logger.info(json);
		String content = WeChatUtils.jsonPostMethodRequest(url.toString(), json);
		logger.info(content);
	}
	
	public static void main(String[] args) {
 		Map<String, Object> data = TemplateMessageUtil.getMessageData(new String[]{"店铺","顺丰","6666888666","2018年6月30日","张三","13760093574","测试","蓝海金融中心"});
		TemplateMessageParam tmp = new TemplateMessageParam();
		tmp.setTouser("oPsXb4rqoA_rEeR7251IfHXowC8s");
		tmp.setTemplateId(TemplateMessageUtil.ORDERS_SEND);//模板ID
		tmp.setFormId("wx2720545653435840972c53973821629473");
		tmp.setEmphasisKeyword("keyword2.DATA");
		tmp.setData(data);//内容
		//TemplateMessageUtil.pullMessage(tmp);
	}
}
